<template>
  <div class="works-display">
    <!-- 加载状态 -->
    <div v-if="isLoading" class="loading-container">
      <a-spin size="large" tip="加载中..." />
    </div>

    <!-- 空状态 -->
    <div v-else-if="works.length === 0" class="empty-container">
      <a-empty description="暂无作品数据" />
    </div>

    <!-- 作品列表 -->
    <div v-else class="works-grid">
      <div 
        class="work-card" 
        v-for="(work, index) in works" 
        :key="work.id" 
        @click="handleWorkClick(work)"
      >
        <!-- 作品状态标签 -->
        <div class="work-status" :class="getStatusClass(work.status)">
          {{ getStatusText(work.status) }}
        </div>

        <!-- 作品封面 -->
        <img 
          :src="getCoverUrl(work.coverFileUrl)" 
          :alt="work.worksName" 
          class="work-cover" 
        />

        <!-- 作品信息 -->
        <div class="work-info">
          <h3 class="work-title" :title="work.worksName">
            {{ work.worksName }}
          </h3>

          <!-- 作品标签 -->
          <div class="work-tags">
            <a-tag
              v-for="(tag, i) in work.tags?.split(',') || []"
              :key="i"
              color="blue"
              size="small"
              v-if="tag"
            >
              {{ tag }}
            </a-tag>
          </div>

          <!-- 作品描述 -->
          <p class="work-desc" :title="work.description">
            {{ work.description || '暂无描述' }}
          </p>

          <!-- 作品元信息 -->
          <div class="work-meta">
            <span class="create-time">
              <CalendarOutlined /> {{ formatDate(work.createTime) }}
            </span>
            <span v-if="work.isCharge === 1" class="price-tag">
              <MoneyOutlined /> {{ work.price || 0 }}元
            </span>
            <span v-else class="free-tag">免费</span>
          </div>

          <!-- 自定义操作按钮 -->
          <div v-if="showActions" class="work-actions">
            <slot name="actions" :work="work">
              <!-- 默认操作按钮 -->
              <a-button size="small" @click.stop="handleView(work)">
                <EyeOutlined /> 查看
              </a-button>
            </slot>
          </div>
        </div>
      </div>
    </div>

    <!-- 分页控制器 -->
    <div class="pagination-container" v-if="showPagination && total > 0 && !isLoading">
      <a-pagination
        v-model:current="currentPage"
        :pageSize="pageSize"
        :total="total"
        show-size-changer
        show-quick-jumper
        :show-total="(total) => `共 ${total} 条记录`"
        @change="handlePageChange"
        @showSizeChange="handlePageSizeChange"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { CalendarOutlined, MoneyOutlined, EyeOutlined } from '@ant-design/icons-vue'

// 作品类型定义（与后端返回数据结构匹配）
interface Work {
  id: number
  userId: number
  worksName: string
  coverFileUrl: string
  description: string
  tags: string
  isCharge: number
  price: number
  status: number
  fileMd5: string
  createTime: string
  updateTime: string
  deleted: number
  videoUrl?: string
  views?: number
}

// 组件属性
interface Props {
  works: Work[] // 作品数据
  loading?: boolean // 加载状态
  showActions?: boolean // 是否显示操作按钮
  showPagination?: boolean // 是否显示分页
  pageSize?: number // 每页条数
  total?: number // 总记录数
  currentPage?: number // 当前页码
}

const props = withDefaults(defineProps<Props>(), {
  loading: false,
  showActions: true,
  showPagination: false,
  pageSize: 10,
  total: 0,
  currentPage: 1
})

// 组件事件
const emit = defineEmits<{
  workClick: [work: Work]
  workView: [work: Work]
  pageChange: [page: number]
  pageSizeChange: [current: number, size: number]
}>()

// 内部状态
const isLoading = ref(props.loading)
const currentPage = ref(props.currentPage)

// 监听外部loading状态变化
watch(() => props.loading, (newLoading) => {
  isLoading.value = newLoading
})

// 监听外部currentPage变化
watch(() => props.currentPage, (newPage) => {
  currentPage.value = newPage
})

// 获取封面URL
const getCoverUrl = (coverFileUrl: string) => {
  if (!coverFileUrl) return ''
  
  const minioUrl = import.meta.env.VITE_MINIO_URL || ''
  
  if (coverFileUrl.startsWith('http')) {
    return coverFileUrl
  }
  
  const cleanCoverPath = coverFileUrl.replace(/^\//, '')
  const baseUrl = minioUrl.endsWith('/') ? minioUrl : `${minioUrl}/`
  return `${baseUrl}${cleanCoverPath}`
}

// 格式化日期
const formatDate = (dateString: string) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleDateString()
}

// 状态文本映射
const getStatusText = (status: number) => {
  const statusMap: Record<number, string> = {
    1: '草稿',
    2: '审核中',
    3: '已发布',
    4: '下架',
    5: '驳回'
  }
  return statusMap[status] || '未知'
}

// 状态样式映射
const getStatusClass = (status: number) => {
  const classMap: Record<number, string> = {
    1: 'status-draft',
    2: 'status-review',
    3: 'status-published',
    4: 'status-offline',
    5: 'status-rejected'
  }
  return classMap[status] || 'status-unknown'
}

// 作品点击事件
const handleWorkClick = (work: Work) => {
  emit('workClick', work)
}

// 查看作品事件
const handleView = (work: Work) => {
  emit('workView', work)
}

// 分页变更处理
const handlePageChange = (page: number) => {
  currentPage.value = page
  emit('pageChange', page)
}

// 每页条数变更处理
const handlePageSizeChange = (current: number, size: number) => {
  currentPage.value = 1
  emit('pageSizeChange', current, size)
}
</script>

<style scoped>
.works-display {
  width: 100%;
  background: #0b2b5b;
  min-height: 400px;
  padding: 20px;
  color: #fff;
}

/* 加载和空状态 */
.loading-container, .empty-container {
  width: 100%;
  padding: 80px 0;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

/* 作品网格布局 */
.works-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 20px;
  margin-bottom: 30px;
}

/* 作品卡片 */
.work-card {
  background: #0f3a72;
  border-radius: 8px;
  padding: 10px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
  transition: transform 0.2s ease, box-shadow 0.2s ease;
  position: relative;
  cursor: pointer;
}

.work-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.3);
}

/* 作品状态标签 */
.work-status {
  position: absolute;
  top: 10px;
  right: 10px;
  padding: 2px 8px;
  border-radius: 12px;
  font-size: 12px;
  z-index: 1;
  color: white;
}

.status-draft { background: #8c8c8c; }
.status-review { background: #faad14; }
.status-published { background: #52c41a; }
.status-offline { background: #1890ff; }
.status-rejected { background: #f5222d; }
.status-unknown { background: #722ed1; }

/* 作品封面 */
.work-cover {
  width: 100%;
  height: 120px;
  object-fit: cover;
  border-radius: 4px;
  margin-bottom: 10px;
}

/* 作品信息 */
.work-info {
  display: flex;
  flex-direction: column;
}

.work-title {
  font-size: 16px;
  font-weight: bold;
  margin: 0 0 8px 0;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  color: #fff;
}

.work-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
  margin-bottom: 6px;
}

.work-desc {
  font-size: 12px;
  color: #c9d8e9;
  margin: 0 0 8px 0;
  line-height: 1.4;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  height: 32px;
}

.work-meta {
  font-size: 12px;
  color: #9eb6d0;
  margin: 0 0 10px 0;
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  align-items: center;
}

.work-meta span {
  display: flex;
  align-items: center;
  gap: 4px;
}

.create-time {
  color: #9eb6d0;
}

.price-tag {
  color: #ff4d4f;
  font-weight: 500;
}

.free-tag {
  color: #52c41a;
  background: rgba(82, 196, 26, 0.1);
  padding: 0 4px;
  border-radius: 2px;
}

/* 操作按钮 */
.work-actions {
  display: flex;
  gap: 8px;
  justify-content: flex-end;
  margin-top: auto;
}

/* 分页容器 */
.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
  padding: 10px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .works-grid {
    grid-template-columns: repeat(auto-fill, minmax(140px, 1fr));
  }
  
  .work-card {
    padding: 8px;
  }
  
  .work-cover {
    height: 100px;
  }
  
  .work-title {
    font-size: 14px;
  }
  
  .work-desc {
    font-size: 11px;
    height: 28px;
  }
}
</style>
